package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    //用户登录
    @Override
    public ResultInfo login(String username, String password) {
        //根据username从数据库中查询,如果查询不到,直接返回错误信息
        Employee employee =employeeMapper.findByUsername(username);
        if (employee==null){
            return ResultInfo.error("该用户不存在");
        }
        //先将前端传入的密码加密(md5)将加密之后的字符串与数据库中的密码串比较,如果失败,返回错误信息
        String passwordWithMd5 = SecureUtil.md5(password);
        String passwordFromDb = employee.getPassword();
        if (!StringUtils.equals(passwordWithMd5,passwordFromDb)){
            return ResultInfo.error("密码错误");
        }
        //判断用户的状态,如果为0,返回错误信息
        if (!employee.getStatus().equals(Employee.STATUS_ENABLE)){
            return ResultInfo.error("该用户未激活");
        }
        //返回成功信息
        return ResultInfo.success(employee);
    }
    //查询员工列表
    @Override
    public List<Employee> findByName(String name) {
        List<Employee> employeeList=employeeMapper.findByName(name);
        return employeeList;
    }
    //添加员工
    @Override
    public void save(Employee employee) {
        //补齐参数
        //id  需要生成唯一的数值  用雪花算数
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //password   md5
        String password = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(password);
        //status  静态只能用类名调用
        employee.setStatus(Employee.STATUS_ENABLE);
        //创建时间跟用户
        //employee.setCreateTime(new Date());
        //employee.setCreateUser(1L);//临时写死
        //更新时间跟用户
        //employee.setUpdateTime(new Date());
        //employee.setUpdateUser(1L);//临时写死
        //调用mapper保存
        employeeMapper.save(employee);
    }
    //根据id查询
    @Override
    public Employee findById(Long id) {
        //调用mapper
        Employee employee=employeeMapper.findById(id);
        return employee;
    }
    //修改
    @Override
    public void update(Employee employee) {
        //设置新的更新时间跟人
        employee.setUpdateTime(new Date());
        //employee.setUpdateUser(1L);//临时写死
        //调用mapper
        employeeMapper.update(employee);
    }
}
